package jp.co.dailyReport.weeklyReport.action;

import java.io.IOException;
import java.util.Vector;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import jp.co.dailyReport.DataUnavailableException;
import jp.co.dailyReport.Utilities;
import jp.co.dailyReport.SystemCalendar;
import jp.co.dailyReport.staff.Staff;
import jp.co.dailyReport.staff.StaffManager;
import jp.co.dailyReport.project.Project;
import jp.co.dailyReport.project.ProjectManager;
import jp.co.dailyReport.project.PjStaff;
import jp.co.dailyReport.project.PjStaffManager;
import jp.co.dailyReport.workItem.WorkItem;
import jp.co.dailyReport.weeklyReport.WeeklyReportWorkItem;
import jp.co.dailyReport.weeklyReport.WeeklyReport;
import jp.co.dailyReport.weeklyReport.WeeklyReportWorkItemManager;

/**
 * 週報登録ページのボタン（追加、確定）
 * が押されたときの処理を管理するクラスです。
 */
public class WeeklyReportConfirmAction extends Action {

	private static Logger log = Logger.getLogger(WeeklyReportConfirmAction.class);

	/**
	 * 週報登録ページのボタン（追加、確定）が押されたときの処理を制御します。<BR>
	 * プロジェクトIDからプロジェクト情報を取得します。<BR>
	 * プロジェクトリーダーの社員IDから、プロジェクトリーダーの社員情報を取得します。<BR>
	 * プロジェクトメンバーの社員IDから、プロジェクトメンバーの社員情報を取得します。<BR>
	 * 作業項目オブジェクト、週報作業項目オブジェクトを、セッションに設定します。<BR><BR>
	 * 
	 * 「追加」ボタンが押された場合の処理：<BR>
	 * 週報クラスのインスタンスを生成し、フィールドに値をセットし、セッションに設定します。<BR>
	 * 
	 * @param mapping このインスタンスを選択するために使用したActionMapping
	 * @param form 存在するならば、このリクエストのためのActionForm Bean
	 * @param request 処理しているHTTPリクエスト
	 * @param response 処理しているHTTPレスポンス
	 * @return ActionForwardインスタンス
	 * @throws IOException, ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		log.debug("WeeklyReportConfirmAction start");
		HttpSession session = request.getSession();
		log.debug("session.getId() = " + session.getId());
		Staff staff = (Staff)session.getAttribute("LoginStaff");
		WeeklyReportWorkItem[] weeklyReportWorkItem = (WeeklyReportWorkItem[])session.getAttribute("weeklyReportWorkItem");
		WorkItem[] workItemList = (WorkItem[])session.getAttribute("workItemList");
		DynaActionForm doWeeklyReportActionForm = (DynaActionForm)form;
		ActionErrors errors = new ActionErrors();

		String target = null;
		Project project = null;
		Staff pLStaff = null;
		Staff[] staffList = null;

		if(request.getParameter("returnTop") != null) {
			target = "returnTop";
			session.removeAttribute("weeklyReportWorkItem");
			session.removeAttribute("workItemList");
			session.removeAttribute("weeklyReport");
		} else {
			if(request.getParameter("add") != null) {
				target = "add";
				Calendar workDateStart = Utilities.getCalendarTime(
				((Integer)doWeeklyReportActionForm.get("workDateStartY")).intValue(),
				((Integer)doWeeklyReportActionForm.get("workDateStartM")).intValue(),
				((Integer)doWeeklyReportActionForm.get("workDateStartD")).intValue(),
				0,0);
				Calendar workDateEnd = Utilities.getCalendarTime(
				((Integer)doWeeklyReportActionForm.get("workDateEndY")).intValue(),
				((Integer)doWeeklyReportActionForm.get("workDateEndM")).intValue(),
				((Integer)doWeeklyReportActionForm.get("workDateEndD")).intValue(),
				0,0);

				WeeklyReport weeklyReport = new WeeklyReport();
				weeklyReport.setWeeklyReportId(((Integer)doWeeklyReportActionForm.get("weeklyReportId")).intValue());
				weeklyReport.setProjectId(((Integer)doWeeklyReportActionForm.get("projectId")).intValue());
				weeklyReport.setStaffId(staff.getStaffId());
				weeklyReport.setWorkDateStart(workDateStart);
				weeklyReport.setWorkDateEnd(workDateEnd);
				weeklyReport.setComment((String)doWeeklyReportActionForm.get("comment"));
				weeklyReport.setProblem((String)doWeeklyReportActionForm.get("problem"));
				session.setAttribute("weeklyReport", weeklyReport);
			}else if(request.getParameter("confirm") != null) {
				target = "confirm";
			}

			try {
				int projectId = ((Integer)doWeeklyReportActionForm.get("projectId")).intValue();
				project = ProjectManager.load(projectId);
				pLStaff = StaffManager.load(project.getPLStaffId());
				PjStaff[] pjStaff = PjStaffManager.getStaffId(projectId);
				staffList = new Staff[pjStaff.length];
				for(int i = 0; i < pjStaff.length; i++) {
					staffList[i] = StaffManager.load(pjStaff[i].getStaffId());
				}
			} catch(DataUnavailableException due) {
				log.error(due.getMessage());
			}

			for(int i = 0; i < weeklyReportWorkItem.length; i++) {
				Calendar deadline = Utilities.getCalendarDate(
														request.getParameter("workItemList[" + i + "].deadlineY"), 
														request.getParameter("workItemList[" + i + "].deadlineM"), 
														request.getParameter("workItemList[" + i + "].deadlineD"));
				workItemList[i].setDeadline(deadline);
				if(Utilities.isNumber(request.getParameter("weeklyReportWorkItem[" + i + "].workingHours"),"double")){
					weeklyReportWorkItem[i].setWorkingHours(Double.parseDouble(request.getParameter("weeklyReportWorkItem[" + i + "].workingHours")));
				}else{
					errors.add("workingHours" + i,new ActionError("errors.workingHours.double"));
				}
			}

			Vector addWeeklyReportWorkItemList = (Vector)session.getAttribute("addWeeklyReportWorkItemList");
			Vector newWrwi = new Vector();
			Vector addWorkItemList = (Vector)session.getAttribute("addWorkItemList");
			WorkItem[] workItem = (WorkItem[])addWorkItemList.toArray(new WorkItem[0]);
			Vector newWi = new Vector();
			double workingHours = 0;
			for(int i = 0; i < addWeeklyReportWorkItemList.size(); i++) {
				WeeklyReportWorkItem wrwi = new WeeklyReportWorkItem();
				Calendar deadline = Utilities.getCalendarDate(
														request.getParameter("addWorkItemList[" + i + "].deadlineY"), 
														request.getParameter("addWorkItemList[" + i + "].deadlineM"), 
														request.getParameter("addWorkItemList[" + i + "].deadlineD"));
				workItem[i].setDeadline(deadline);

				if(Utilities.isNumber(request.getParameter("addWeeklyReportWorkItemList1[" + i + "].workingHours"),"double")){
					wrwi.setWorkingHours(Double.parseDouble(request.getParameter("addWeeklyReportWorkItemList1[" + i + "].workingHours")));
					workingHours = workingHours + Double.parseDouble(request.getParameter("addWeeklyReportWorkItemList1[" + i + "].workingHours"));
				}else{
					errors.add("addWorkingHours" + i,new ActionError("errors.addWorkingHours.double"));
				}
				newWi.add(workItem[i]);
				newWrwi.add(wrwi);
			}
			session.setAttribute("addWorkItemList", newWi);
			session.setAttribute("addWeeklyReportWorkItemList", newWrwi);
			try{
				doWeeklyReportActionForm.set("totalHoursWorked", new Double(WeeklyReportWorkItemManager.calculate(weeklyReportWorkItem) + workingHours));
				request.setAttribute("allStaffList", StaffManager.load());
			} catch(DataUnavailableException due) {
				log.error(due.getMessage());
			}
			if (!errors.isEmpty()){
				target = "add";
				saveErrors(request,errors);
			}
			session.setAttribute("workItemList", workItemList);
			session.setAttribute("weeklyReportWorkItem", weeklyReportWorkItem);
			request.setAttribute("project", project);
			request.setAttribute("pLStaff", pLStaff);
			request.setAttribute("staffList", staffList);
			request.setAttribute("systemCalendar", new SystemCalendar());
		}

		log.debug("WeeklyReportConfirmAction end");
		return mapping.findForward(target);
	}
}
